<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/24 0024
 * Time: 下午 9:32
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\WXBizDataCrypt;

use think\Config;
use think\Db;

class Weixin extends Api
{
	
	protected $noNeedLogin = ['index', 'getshareconfig'];
	
	/**
	 * 响应微信的方法
	 */
	public function index()
	{
		echo $_GET['echostr'];
	}
	/**
	 * h5分享配置
	 */
	public function getShareConfig() {
		$url = urldecode($this->request->post('url'));
		
		
		$config = config('weixin.public');
		$appId = $config['app_id'];
		$weixin = new \app\common\library\Weixin($appId);
		$resData = [
			'noncestr' => $weixin->createNoncestr(),
			'timestamp' => (string)time(),
			'jsapi_ticket' => $weixin->getTicket(),
			'url' => $url,
		];
		
		ksort($resData);
		$String = \app\common\library\Weixin::formatBizQueryParaMap($resData, false);
		
		$resData['app_id'] = $appId;
		$resData['signature'] = sha1($String);
		
		$this->success('成功', $resData);
	}
	
	
	/**
	 * 创建二维码
	 */
	public function createQrCode() {
		$path = urldecode($this->request->post('path'));
		$config = config('weixin');
		$appid = $config['smallapp']['app_id'];
		$weixin = new \app\common\library\Weixin($appid);
		$url = $weixin->createQrCode($path);
		if($url) {
			$this->success('创建成功'.$path, $url);
		} else {
			$this->error('二维码创建出错');
		}
	}
	
	/**
	 * 绑定用户微信绑定的手机号
	 */
	public function bindPhone()
	{
		
		$iv = input('post.iv');
		$encryptedData = input('post.encryptedData');
		$code = input('post.code');
		
		$userId = $this->auth->id;
		
		$data = [];
		$config = Config::get('weixin.smallapp');
		//原来的不行才重新获取
		//获取openid和session_key
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $config['app_id'] . '&secret=' . $config['app_secret'] . '&js_code=' . $code . '&grant_type=authorization_code';
		$res = curl_get_info($url);
		
		if (!$res || isset($res['errcode'])) {
			$this->error('授权出错，请重试', $res);
		}
		
		$sessionKey = $res['session_key'];
		$pc = new WXBizDataCrypt($config['app_id'] , $sessionKey);
		
		//解密数据
		$errCode = $pc->decryptData($encryptedData, $iv, $data);
		
		
		if ($errCode == 0) {
			$data = json_decode($data, true);
			
			//解压后的手机号
			$phone = $data['purePhoneNumber'];
			
			//查找该手机号已经有绑定了用户，有直接绑定微信信息后登录，否则是新用户
			$res = Db::name('user')
				->where(['id' => $userId])
				->update(['mobile' => $phone]);
			
			if($res !== false) {
				$this->success('操作成功', $this->auth->getUserinfo());
			}
			
			$this->error('操作出错，请重试');
			
		} else {
			$data = [
				'iv' => $iv,
				'encryptedData' => $encryptedData,
				'code' => $code,
				'session_key' => $sessionKey,
				'errCode' => $errCode,
			];
			$this->error('授权出错，请重试', $data);
		}
	}
}
